import { useEffect, useReducer } from 'react'

const fetchReducer = (state, action) => {
  switch (action.type) {
    case 'PENDING':
      return {
        ...state,
        loading: true,
        error: false
      }
    case 'FULFILLED':
      return {
        ...state,
        loading: false,
        error: false,
        data: action.payload
      }
    case 'REJECTED':
      return {
        ...state,
        loading: false,
        error: true
      }
    default:
      throw new Error()
  }
}

const useApi = (api, params) => {
  const [state, dispatch] = useReducer(fetchReducer, {
    loading: false,
    error: false,
    data: {}
  })

  useEffect(() => {
    const fetchData = async () => {
      dispatch({ type: 'PENDING' })
      try {
        const data = await api(params)
        dispatch({ type: 'FULFILLED', payload: data })
      } catch (error) {
        dispatch({ type: 'REJECTED' })
      }
    }
    fetchData()
  }, [params])

  return [state]
}

export default useApi
